//
//  SAPermissionsSetVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2022/5/12.
//

#import "SAPermissionsSetVC.h"
#import "SAStaffManagementModel.h"
#import "SAPermissionsModel.h"
#import "SAPermissionsHeaderView1.h"
#import "SAPermissionsHeaderView2.h"
#import "SAPermissionsCell2.h"
#import "SASystemEmpUpdateAPI.h"

@interface SAPermissionsSetVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate>

@property (nonatomic, strong) SAStaffManagementModel *model;
@property (nonatomic, strong) UIButton *completeBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SAPermissionsModel *permissionsModel;
@property (nonatomic, strong) SASystemEmpUpdateAPI *systemEmpUpdateAPI;
@property (nonatomic, strong) NSString *merchantId;

@end

@implementation SAPermissionsSetVC

-(instancetype)initWithModel:(SAStaffManagementModel *)model AndMerchantId:(NSString *)merchantId {
    if (self = [super init]) {
        self.model = model;
        self.merchantId = merchantId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemEmpUpdateAPI == api) {
        [Prompt popPromptViewWithMsg:@"修改权限成功" duration:2];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    NSDictionary *dic = error.userInfo;
    NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
    [Prompt popPromptViewWithMsg:msg duration:2];
}

-(void)loadData:(NSString *)empId {
    [SANetManager requestWithType:SkyHttpRequestTypeGet urlString:SA_BASE_URL(@"/system/emp/detail") parameters:@{@"empId" : empId, @"merchantId" : self.merchantId} successBlock:^(id responseObject) {
        self.permissionsModel = [SAPermissionsModel mj_objectWithKeyValues:responseObject];
        for (SAPermsMenuListModel *list in self.permissionsModel.menuList) {
            if (list.perms.count == 0) {
                
            }else {
                NSInteger i = list.perms.count % 3;
                NSInteger n = 0;
                if (i == 1) {
                    n = 2;
                }
                if (i == 2) {
                    n = 1;
                }
                for (int j = 0; j < n; j++) {
                    SAPermsModel *model = [SAPermsModel new];
                    model.noShow = YES;
                    [list.perms addObject:model];
                }
                NSMutableArray *permsList = [NSMutableArray array];
                for (int k = 0; k < list.perms.count; k++) {
                    SAPermsListModel *model = [SAPermsListModel new];
                    model.perms1 = list.perms[k];
                    k++;
                    model.perms2 = list.perms[k];
                    k++;
                    model.perms3 = list.perms[k];
                    [permsList addObject:model];
                }
                list.permsList = permsList;
            }
        }
        [self.tableView reloadData];
        [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
    } failureBlock:^(NSString *error) {
        
    }];
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.permissionsModel.menuList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.permissionsModel.menuList[section].permsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SAPermissionsCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"SAPermissionsCell2" forIndexPath:indexPath];
    SAPermsListModel *model = self.permissionsModel.menuList[indexPath.section].permsList[indexPath.row];
    cell.model = model;
    cell.userInteractionEnabled = YES;
    cell.updateStatusBlock = ^{
        [weakSelf updateCheckStatus:indexPath.section];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(45);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    WeakSelf
    if (section == 0) {
        SAPermissionsHeaderView1 *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SAPermissionsHeaderView1"];
        SAPermsMenuListModel *model = self.permissionsModel.menuList[section];
        headerView.model = model;
        headerView.userInteractionEnabled = YES;
        headerView.updateStatusBlock = ^{
            [weakSelf updateHeaderCheckStatus:section];
        };
        return headerView;
    }
    SAPermissionsHeaderView2 *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SAPermissionsHeaderView2"];
    SAPermsMenuListModel *model = self.permissionsModel.menuList[section];
    headerView.model = model;
    headerView.userInteractionEnabled = YES;
    headerView.updateStatusBlock = ^{
        [weakSelf updateHeaderCheckStatus:section];
    };
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return kScaleNum(90);
    }
    return kScaleNum(45);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

//更新状态
-(void)updateHeaderCheckStatus:(NSInteger)index {
    SAPermsMenuListModel *model = self.permissionsModel.menuList[index];
    NSString *isDelete = model.isDelete;
    for (SAPermsModel *permModel in model.perms) {
        if (permModel.noShow != YES) {
            permModel.isDelete = isDelete;
        }
    }
    [self.tableView reloadData];
}

-(void)updateCheckStatus:(NSInteger)index {
    if (!(index == 1 || index == 6)) {
        SAPermsMenuListModel *model = self.permissionsModel.menuList[index];
        NSInteger num = 0;
        NSInteger showPerms = 0;
        for (SAPermsModel *permModel in model.perms) {
            if (permModel.noShow != YES) {
                showPerms ++;
                if (![permModel.isDelete isEqualToString:@"0"]) {
                    num ++;
                }
            }
        }
        if (num == showPerms) {
            model.isDelete = @"1";
        }
    }
    [self.tableView reloadData];
}

#pragma mark - event
-(void)confirmationTapEvent {
    NSMutableDictionary *permsDict = [[NSMutableDictionary alloc] init];
    NSMutableArray<SACommonPermsModel *> *commonPerms = self.permissionsModel.commonPerms;
    NSMutableArray<SAPermsMenuListModel *> *menuList = self.permissionsModel.menuList;
    for (SACommonPermsModel * model in commonPerms) {
        [permsDict setValue:model.isDelete forKey:model.empMenuId];
    }
    for (SAPermsMenuListModel * model in menuList) {
        [permsDict setValue:model.isDelete forKey:model.empMenuId];
        for (SAPermsModel *perm in model.perms) {
            if (perm.noShow != YES) {
                [permsDict setValue:perm.isDelete forKey:perm.empMenuId];
            }
        }
    }
    
    self.systemEmpUpdateAPI.empId = self.model.empId;
    self.systemEmpUpdateAPI.empType = self.model.empType;
    self.systemEmpUpdateAPI.enable = self.model.enable;
    self.systemEmpUpdateAPI.empName = self.model.empName;
    self.systemEmpUpdateAPI.mobile = self.model.mobile;
    self.systemEmpUpdateAPI.userName = self.model.userName;
    if (self.permissionsModel != nil) {
        self.systemEmpUpdateAPI.menuMap = permsDict;
    }
    [self.systemEmpUpdateAPI sendRequestToServerWithActivityViewAndMask:POST];
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"权限设置"];
    [self setBgImage:nil];
    [self addRightViews:@[self.completeBtn]];
    [self.view addSubview:self.tableView];
    [self loadData:self.model.empId];
}

#pragma mark - lazy init
-(UIButton *)completeBtn {
    if (!_completeBtn) {
        _completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_completeBtn setTitle:@"完成" forState:UIControlStateNormal];
        _completeBtn.frame = SARectMake(254, 0, 85, 44);
        _completeBtn.titleLabel.font = kFont(18);
        [_completeBtn addTarget:self action:@selector(confirmationTapEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    return _completeBtn;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kLineColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAPermissionsCell2 class] forCellReuseIdentifier:@"SAPermissionsCell2"];
        [_tableView registerClass:[SAPermissionsHeaderView1 class] forHeaderFooterViewReuseIdentifier:@"SAPermissionsHeaderView1"];
        [_tableView registerClass:[SAPermissionsHeaderView2 class] forHeaderFooterViewReuseIdentifier:@"SAPermissionsHeaderView2"];
    }
    return _tableView;
}

-(SASystemEmpUpdateAPI *)systemEmpUpdateAPI {
    if (!_systemEmpUpdateAPI) {
        _systemEmpUpdateAPI = [SASystemEmpUpdateAPI apiWithDelegate:self];
    }
    return _systemEmpUpdateAPI;
}

@end
